package org.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.example.domain.ResponseResult;
import org.example.domain.dto.MessageListDto;
import org.example.domain.entity.Message;
import org.example.domain.entity.User;
import org.example.domain.vo.MessageListVo;
import org.example.domain.vo.PageVo;
import org.example.mapper.MessageMapper;
import org.example.mapper.UserMapper;
import org.example.service.MessageService;
import org.example.utils.BeanCopyUtils;
import org.example.utils.SecurityUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
@RequiredArgsConstructor
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements MessageService {


    private final MessageMapper messageMapper;

    private final UserMapper userMapper;

    @Override
    public ResponseResult sendMessage(Message message) {
        Integer id = SecurityUtils.getUserId();
        message.setUserId(id);
        return ResponseResult.okResult(save(message));
    }

    @Override
    public ResponseResult allMessageList() {
        List<Message> messages = messageMapper.allMessageList();

        for(Message message : messages){
            if(message.getUserId() == null){
                continue;
            }
            User user = userMapper.SelectByUserId(message.getUserId());
            if(!Objects.isNull(user)) {
                message.setUsername(user.getUserName());
                message.setAvatar(user.getAvatar());
            }
        }
        List<MessageListVo> messageListVos = BeanCopyUtils.copyBeanList(messages, MessageListVo.class);
        return ResponseResult.okResult(messageListVos);
    }

    @Override
    public ResponseResult messageList(MessageListDto messageListDto) {
        LambdaQueryWrapper<Message> queryWrapper = new LambdaQueryWrapper<>();
        if(messageListDto.getStatus() != null) {
            queryWrapper.eq(Message::getStatus,messageListDto.getStatus());
        }
        Page<Message> page = new Page<>();
        page.setCurrent(messageListDto.getPageNum());
        page.setSize(messageListDto.getPageSize());
        page(page,queryWrapper);
        PageVo pageVo = new PageVo(page.getRecords(),page.getTotal());
        return ResponseResult.okResult(pageVo);
    }

    @Override
    public ResponseResult updateMessage(Message message) {
        Integer id = SecurityUtils.getUserId();
        message.setUserId(id);
        return ResponseResult.okResult(updateById(message));
    }
}
